package persistence

import (
	"github.com/yourusername/book-management-system/internal/domain/model"
	"github.com/yourusername/book-management-system/internal/domain/repository"
	"gorm.io/gorm"
)

type bookRepository struct {
	db *gorm.DB
}

func NewBookRepository(db *gorm.DB) repository.BookRepository {
	return &bookRepository{db: db}
}

func (r *bookRepository) Create(book *model.Book) error {
	return r.db.Create(book).Error
}

func (r *bookRepository) Update(book *model.Book) error {
	return r.db.Save(book).Error
}

func (r *bookRepository) Delete(id uint) error {
	return r.db.Delete(&model.Book{}, id).Error
}

func (r *bookRepository) FindByID(id uint) (*model.Book, error) {
	var book model.Book
	err := r.db.First(&book, id).Error
	return &book, err
}

func (r *bookRepository) FindByISBN(isbn string) (*model.Book, error) {
	var book model.Book
	err := r.db.Where("isbn = ?", isbn).First(&book).Error
	return &book, err
}

func (r *bookRepository) FindAll(page, pageSize int) ([]*model.Book, int64, error) {
	var books []*model.Book
	var total int64

	err := r.db.Model(&model.Book{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	offset := (page - 1) * pageSize
	err = r.db.Offset(offset).Limit(pageSize).Find(&books).Error
	return books, total, err
}

func (r *bookRepository) Search(query string, page, pageSize int) ([]*model.Book, int64, error) {
	var books []*model.Book
	var total int64

	searchQuery := "%" + query + "%"
	countQuery := r.db.Model(&model.Book{}).
		Where("title LIKE ? OR author LIKE ? OR isbn LIKE ?", searchQuery, searchQuery, searchQuery)

	err := countQuery.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	offset := (page - 1) * pageSize
	err = countQuery.Offset(offset).Limit(pageSize).Find(&books).Error
	return books, total, err
}

func (r *bookRepository) UpdateStatus(id uint, status model.BookStatus) error {
	return r.db.Model(&model.Book{}).Where("id = ?", id).Update("status", status).Error
}
